<template>
    <div class="account-detail">
        <div class="header">
            <h1>账户设置</h1>
        </div>

        <el-card shadow="never" class="auth-card">
            <template #header>
                <div class="card-header">实名认证</div>
            </template>
            <el-row class="auth-row">
                <el-col :span="18">
                    <span>实名认证</span>
                </el-col>
                <el-col :span="6" class="text-right">
                    <span v-if="userInfo.cardID">已认证</span>
                    <el-link v-else :underline="false" type="primary" @click="goAuth"
                        class="link-with-arrow custom-link">
                        去认证
                        <el-icon class="arrow-icon">
                            <arrow-right />
                        </el-icon>
                    </el-link>
                </el-col>
            </el-row>
        </el-card>

        <el-card shadow="never" class="bind-card">
            <template #header>
                <div class="card-header">安全与绑定</div>
            </template>
            <el-row class="bind-row">
                <el-col :span="18">
                    <span>手机号</span>
                </el-col>
                <el-col :span="6" class="text-right">

                    <el-link :underline="false" type="primary" @click="updataPhoneNumAction"
                        class="link-with-arrow custom-link">


                        <span v-if="userInfo.isbindphone">{{ formatPhone(userInfo.phone) }}</span>
                        <span v-else>去绑定</span>
                        <el-icon class="arrow-icon">
                            <arrow-right />
                        </el-icon>
                    </el-link>

                </el-col>
            </el-row>
            <el-row class="bind-row">
                <el-col :span="18">
                    <span>登录密码</span>
                </el-col>
                <el-col :span="6" class="text-right">
                    <el-link :underline="false" type="primary" @click="setPassword" class="link-with-arrow custom-link">
                        <span v-if="userInfo.unsetPassword">未设置</span>
                        <span v-else>去修改</span>
                        <el-icon class="arrow-icon">
                            <arrow-right />
                        </el-icon>
                    </el-link>
                </el-col>
            </el-row>
            <!-- <el-row class="bind-row">
                <el-col :span="18">
                    <span>微信</span>
                </el-col>
                <el-col :span="6" class="text-right custom-link">
                    <el-link :underline="false" type="primary" @click="bindWechat" class="link-with-arrow custom-link">
                        <span v-if="userInfo.isbindwxqq == 1||userInfo.isbindwxqq == 3">已绑定</span>
                        <span v-else>未绑定</span>
                        <el-icon class="arrow-icon">
                            <arrow-right />
                        </el-icon>
                    </el-link>
                </el-col>
            </el-row> -->
        </el-card>

        <el-dialog :append-to-body="true" title="" class="psd-dialog" v-model="updataPswdialogVisible" width="430">
            <div class="psd-dialog-content">
                <h3>修改登录密码</h3>
                <div class="account-info">当前账号：{{ formatPhone(userInfo.phone) }}</div>
                <el-form ref="updataPswFormRef" :model="updataPswform" label-width="120px" label-position="top"
                    :rules="updataPswRules" hide-required-asterisk>
                    <el-form-item label="短信验证码" prop="smsCode">
                        <el-input class="inputV" v-model="updataPswform.smsCode" clearable placeholder="请输入短信验证码">
                            <template #suffix>
                                <el-button type="text" @click="getVerificationCode" :disabled="countDown > 0" :style="{
                                    color: countDown > 0 ? '#888888' : '#FFE500',
                                    padding: '0 15px', // 调整按钮内边距
                                    fontSize: '14px'   // 调整文字大小
                                }">
                                    {{ countDown > 0 ? `${countDown}` : '获取验证码' }}
                                </el-button>
                            </template>
                        </el-input>

                    </el-form-item>
                    <el-form-item label="请输入新密码" prop="newPassword">
                        <el-input class="inputV" v-model="updataPswform.newPassword" clearable type="password"
                            placeholder="请输入新密码" />
                    </el-form-item>
                    <el-form-item label="请再次确认密码" prop="confirmPassword">
                        <el-input class="inputV" v-model="updataPswform.confirmPassword" clearable type="password"
                            placeholder="请再次确认密码" />
                    </el-form-item>
                    <el-form-item>
                        <el-button class="okbtn" type="" @click="confirmModify" :style="{
                            backgroundColor: isBtnActive ? '#FFE500' : '#232527',
                            color: isBtnActive ? '#121212' : '#888888',
                        }">
                            确定
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>

        <el-dialog :append-to-body="true" title="" class="psd-dialog" v-model="updataPhonedialogVisible" width="430">
            <div class="psd-dialog-content">
                <h3>设置换绑手机号</h3>
                <el-form class="updataPhoneForm" ref="updataPhoneFormRef" :model="updataPhoneform" label-width="120px"
                    label-position="top" :rules="updataPhoneRules" hide-required-asterisk>
                    <el-form-item label="请输入换绑手机号" prop="PhoneNum">
                        <el-input class="inputV" v-model="updataPhoneform.PhoneNum" clearable placeholder="请输入换绑手机号" />
                    </el-form-item>

                    <el-form-item label="短信验证码" prop="smsCode">
                        <el-input class="inputV" v-model="updataPhoneform.smsCode" clearable placeholder="请输入短信验证码">

                            <template #suffix>
                                <el-button type="text" @click="updataPhonegetVerificationCode" :disabled="countDown > 0"
                                    :style="{
                                        color: countDown > 0 ? '#888888' : '#FFE500',
                                        padding: '0 15px', // 调整按钮内边距
                                        fontSize: '14px'   // 调整文字大小
                                    }">
                                    {{ countDown > 0 ? `${countDown}` : '获取验证码' }}
                                </el-button>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button class="okbtn" type="primary" @click="updataPhoneconfirmModify" :style="{
                            backgroundColor: isBtnActive2 ? '#FFE500' : '#232527',
                            color: isBtnActive2 ? '#121212' : '#888888',
                        }">
                            确定
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>

        <el-dialog :append-to-body="true" title="" v-model="bindWechatdialogVisible" class="psd-dialog" width="430"
            center>
            <div class="wechatQrCode">
                <div class="title">
                    <img src="@/assets/images/usercenter/user_wechat.png" alt="" />
                    <span class="qrtext1">使用微信扫码</span>
                </div>

                <div class="qrtext2">绑定后可使用微信扫码快速登录</div>
                <div class="qrbgV">
                    <QrcodeVue v-if="qrCodeImg" :value="qrCodeImg" :size="160" class="qr-code-img"
                        style="overflow: hidden;" />
                </div>
            </div>
        </el-dialog>

        <!-- 实名认证弹窗 -->
        <RealName v-model="showRealName" @close="showRealName = false" />
    </div>
</template>

<script setup>
defineOptions({
    name: 'AccountSettings'
})
import { ref, onMounted, computed, watch } from 'vue';
import { ElLink, ElCard, ElRow, ElCol } from 'element-plus'
import { domesticUserCenter } from 'ld-web-sdk';
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import RealName from '@/components/RealName.vue'

import successIcon from '@/assets/images/success-icon.png'
import errorIcon from '@/assets/images/error-icon.png'
import warningIcon from '@/assets/images/warning-icon.png'


const router = useRouter()
const userStore = useUserStore()
// 获取用户信息 
const userInfo = computed(() => userStore.userInfo)

const updataPswdialogVisible = ref(false);
const updataPswFormRef = ref(null);
const updataPswform = ref({
    smsCode: '',
    newPassword: '',
    confirmPassword: ''
});
const updataPhonedialogVisible = ref(false);
const updataPhoneform = ref({
    PhoneNum: '',
    smsCode: '',
});
const updataPhoneFormRef = ref(null);
const bindWechatdialogVisible = ref(false)
const countDown = ref(0); // 倒计时秒数
const showRealName = ref(false)
const qrCodeImg = ref('');

const updataPhoneRules = ref({
    smsCode: [
        { required: true, message: '请输入短信验证码', trigger: 'blur' },
    ],
    PhoneNum: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        {
            pattern: /^1[3-9]\d{9}$/, // 手机号正则：以1开头，第二位3-9，后9位数字
            message: '请输入正确的手机号格式',
            trigger: 'blur'
        }
    ],

})
const updataPswRules = ref({
    smsCode: [
        { required: true, message: '请输入短信验证码', trigger: 'blur' },
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 8, message: '密码长度不能少于8位', trigger: 'blur' },
        { max: 16, message: '密码长度不能超过16位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请再次确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== updataPswform.value.newPassword) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
})



const formatPhone = (phone) => {
    // 检查手机号是否存在且为11位
    if (phone && phone.length === 11) {
        // 保留前3位和后4位，中间4位用*代替
        return phone.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3');
    }
    // 不符合格式时返回原始值
    return phone;
};

//换绑 获取验证码
const updataPhonegetVerificationCode = () => {
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(updataPhoneform.value.PhoneNum)) {
        ElMessage.error('手机号格式错误')
        return; // 不发送验证码
    }
    // 开始倒计时
    countDown.value = 60;
    const timer = setInterval(() => {
        countDown.value--;
        if (countDown.value <= 0) {
            clearInterval(timer);
        }
    }, 1000);
    //发送验证码
    handleGetSmsCode(updataPhoneform.value.PhoneNum)
};

//接口  发送验证码
const handleGetSmsCode = async (PhoneNum) => {
    console.log('PhoneNum===>', PhoneNum);
    // API请求
    domesticUserCenter.sendSms({
        phone: PhoneNum,
    }).then(res => {
        if (res.code == 200) {
            ElMessage.success('验证码发送成功')
        }
    }).catch(err => {
        console.log('sendSms err', err)
    })
};


//修改密码 获取验证码
const getVerificationCode = () => {
    // 开始倒计时
    countDown.value = 60;
    const timer = setInterval(() => {
        countDown.value--;
        if (countDown.value <= 0) {
            clearInterval(timer);
        }
    }, 1000);

    //发送验证码
    if (userStore.userInfo) {
        handleGetSmsCode(userStore.userInfo.phone)
    }

};

const isBtnActive = computed(() => {
    return updataPswform.value.smsCode && updataPswform.value.newPassword && updataPswform.value.confirmPassword;
});
const isBtnActive2 = computed(() => {
    return updataPhoneform.value.smsCode && updataPhoneform.value.PhoneNum;
});

//修改密码 提交
const confirmModify = () => {
    updataPswFormRef.value.validate((valid) => {
        if (valid) {
            domesticUserCenter.createModifyPwd().phone({
                phone: userStore.userInfo.phone,
                newPwd: updataPswform.value.newPassword,
                auth: updataPswform.value.smsCode
            }).then(res => {
                if (res.code == 200) {
                    ElMessage({
                        type: 'success',
                        customClass: 'custom-success-message-icon',
                        dangerouslyUseHTMLString: true,
                        message: `<img src="${successIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">修改成功`,
                        offset: 65
                    })
                    updataPswdialogVisible.value = false;
                    userStore.RefreshUserInfo()
                    //退出登录 返回首页
                    userStore.logout()
                    router.push('/')
                    emit('close')
                }
            }).catch(err => {
                ElMessage({
                    type: 'error',
                    customClass: 'custom-success-message-icon',
                    dangerouslyUseHTMLString: true,
                    message: `<img src="${errorIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">${err.message}`,
                    offset: 65
                })
            })
        } else {
            // 验证失败
            console.log('表单验证失败');
            return false;
        }
    });
};



//设置换绑手机号 提交
const updataPhoneconfirmModify = () => {
    // 验证表单
    updataPhoneFormRef.value.validate((valid) => {
        if (valid) {
            domesticUserCenter.createUpdateUser().bindPhone({
                phone: updataPhoneform.value.PhoneNum,
                auth: updataPhoneform.value.smsCode
            }).then(res => {
                console.log('res', res)
                if (res.code == 200) {
                    ElMessage({
                        type: 'success',
                        customClass: 'custom-success-message-icon',
                        dangerouslyUseHTMLString: true,
                        message: `<img src="${successIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">绑定成功`,
                        offset: 65
                    })
                    updataPhonedialogVisible.value = false;
                    userStore.RefreshUserInfo()
                    //退出登录 返回首页
                    userStore.logout()
                    router.push('/')
                }
            }).catch(err => {
                ElMessage({
                    type: 'error',
                    customClass: 'custom-success-message-icon',
                    dangerouslyUseHTMLString: true,
                    message: `<img src="${errorIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">${err.message}`,
                    offset: 65
                })
            })

        } else {
            // 验证失败
            console.log('表单验证失败');
            return false;
        }
    });
};

const goAuth = () => {
    // 去实名认证的逻辑
    showRealName.value = true

}

const setPassword = () => {
    // 设置登录密码的逻辑
    console.log('设置登录密码')
    updataPswdialogVisible.value = true;
}

const updataPhoneNumAction = async () => {
    updataPhonedialogVisible.value = true;
    return false;
    // 设置登录密码的逻辑
    console.log('换绑手机号码')
    if (!userStore.userInfo.isbindphone) {
        updataPhonedialogVisible.value = true;
    }


}

const bindWechat = async () => {
    // 绑定微信的逻辑
    let qrCodeRes = await domesticUserCenter.createLoginQrcode()

    if (qrCodeRes.code == 200) {
        console.log("qrCodeRes.data", qrCodeRes.data);
    }

    // reginRes.bindWechat().then(res => {
    //     if (res.code == 200) {
    //         ElMessage.success('二维码生成成功')
    //     }
    // }).catch(err => {
    //     console.log('createLoginQrcode err', err)
    // })

    bindWechatdialogVisible.value = true;
}
onMounted(() => {
    userStore.RefreshUserInfo()
})

// Emits
const emit = defineEmits(['update:modelValue', 'close'])

// 清空修改密码表单
const clearPasswordForm = () => {
    if (updataPswFormRef.value) {
        updataPswFormRef.value.resetFields();
    }
    updataPswform.value = {
        smsCode: '',
        newPassword: '',
        confirmPassword: ''
    };
};

// 清空手机号绑定表单
const clearPhoneForm = () => {
    if (updataPhoneFormRef.value) {
        updataPhoneFormRef.value.resetFields();
    }
    updataPhoneform.value = {
        PhoneNum: '',
        smsCode: ''
    };
};

// 监听修改密码弹窗关闭事件，清空表单
watch(
    () => updataPswdialogVisible.value,
    (newValue) => {
        if (!newValue) {
            clearPasswordForm();
        }
    }
);

// 监听换绑手机号弹窗关闭事件，清空表单
watch(
    () => updataPhonedialogVisible.value,
    (newValue) => {
        if (!newValue) {
            clearPhoneForm();
        }
    }
);

</script>

<style lang="scss" scoped>
.account-detail {
    padding: 20px;
    box-sizing: border-box;

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h1 {
            font-size: 24px;
            margin: 0;
            color: #E2E2E2;
            font-weight: bold;
        }
    }

    :deep(.el-card__header) {
        border-bottom: none !important;
    }

    .auth-row,
    .bind-row {
        padding: 20px 20px;
        background: #27292C;
    }

    .auth-row:last-child,
    .bind-row:last-child {
        border-bottom: none;
    }

    .auth-card,
    .bind-card {
        margin-bottom: 20px;
    }

    .card-header {
        font-weight: bold;
        font-size: 16px;
        color: #888888;
    }
}




.link-with-arrow {
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.arrow-icon {
    font-size: 16px;
    transition: transform 0.2s;
}

.el-link:hover .arrow-icon {
    transform: translateX(2px);
}

/* 自定义el-link样式，设置文字颜色为#888888 */
.custom-link {
    color: #888888 !important;
    font-size: 14px !important;
}

.custom-link:hover {
    color: #666666 !important;
    /* 悬停时稍微加深颜色 */
}

.custom-link:hover .arrow-icon {
    transform: translateX(2px);
    color: #666666;
}

.account-info {
    margin: 15px 0 30px 0;
    color: #888888;
}

.inputV {
    height: 50px;
    font-size: 14px;
}

.okbtn {
    width: 100%;
    height: 50px;
    border: none;
}



:deep(.el-dialog__title) {
    color: #fff !important;
    font-size: 24px;
}


:deep(.el-input__wrapper) {
    box-shadow: none
}


.qrtext1 {
    font-weight: 700;
    font-style: Bold;
    font-size: 24px;
}
</style>
<style lang="scss">
.psd-dialog {
    box-sizing: border-box;

    .el-dialog__header {
        padding: 20px !important;

        .el-dialog__title {
            color: #fff;
            font-size: 24px;
            font-weight: bold;
        }
    }

    .el-dialog__body {
        padding: 30px 40px;

        h3 {
            font-size: 24px;
            font-weight: bold;
            color: #fff;
        }

        .el-form-item__label {
            color: #888;
        }
    }

    .psd-dialog-content {
        .updataPhoneForm {
            margin-top: 30px;
        }
    }

    .wechatQrCode {
        .title {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: #fff;

            image {
                margin-right: 10px;
            }
        }

        .qrtext2 {
            margin-top: 10px;
            font-size: 14px;
            text-align: center;
        }

        .qrbgV {
            width: 196px;
            height: 196px;
            margin: 20px auto;
            background: #fff;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;

            .qrimage {
                width: 156px;
                height: 156px;
                display: block;
            }
        }
    }
}
</style>
